package com.funsport.controller.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.common.PageResult;
import com.funsport.common.Result;
import com.funsport.entity.Club;
import com.funsport.entity.ClubMember;
import com.funsport.security.DataPermissionHelper;
import com.funsport.security.SecurityUtils;
import com.funsport.service.IClubService;
import com.funsport.service.IClubMemberService;

import java.util.List;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Tag(name = "Web管理端俱乐部", description = "Web管理端俱乐部管理接口")
@RestController
@RequestMapping("/web/club")
@RequiredArgsConstructor
public class WebClubController {

    private final IClubService clubService;
    private final IClubMemberService clubMemberService;
    private final DataPermissionHelper dataPermissionHelper;

    @Operation(summary = "获取俱乐部列表")
    @PreAuthorize("hasAnyRole('ADMIN', 'VENUE_MANAGER', 'CLUB_MANAGER')")
    @GetMapping("/list")
    public Result<PageResult<Club>> getClubList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        // 数据权限过滤：俱乐部管理员只能看到自己创建的俱乐部
        LambdaQueryWrapper<Club> queryWrapper = new LambdaQueryWrapper<>();
        
        if (dataPermissionHelper.isClubManager() && !dataPermissionHelper.canViewAllData()) {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            queryWrapper.eq(Club::getCreatorId, currentUserId);
            log.info("俱乐部管理员数据过滤: userId={}", currentUserId);
        }
        
        queryWrapper.orderByDesc(Club::getCreatedAt);
        
        Page<Club> pageParam = new Page<>(page, pageSize);
        Page<Club> result = clubService.page(pageParam, queryWrapper);
        
        return Result.success(PageResult.build(
                result.getRecords(), result.getTotal(), page, pageSize));
    }

    @Operation(summary = "审核俱乐部")
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/{id}/approve")
    public Result<Void> approveClub(@PathVariable Long id) {
        // TODO: 实现审核逻辑
        return Result.success();
    }

    @Operation(summary = "获取俱乐部成员列表")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN')")
    @GetMapping("/{id}/members")
    public Result<List<ClubMember>> getClubMembers(
            @PathVariable Long id,
            @RequestParam(required = false) String status) {
        List<ClubMember> members = clubMemberService.getClubMembers(id, status);
        return Result.success(members);
    }

    @Operation(summary = "审核加入申请")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN')")
    @PostMapping("/member/{memberId}/approve")
    public Result<Void> approveMember(
            @PathVariable Long memberId,
            @RequestParam Boolean approved) {
        Long operatorId = SecurityUtils.getCurrentUserId();
        clubMemberService.approveJoinRequest(memberId, approved, operatorId);
        return Result.success(approved ? "已通过申请" : "已拒绝申请", null);
    }

    @Operation(summary = "踢出成员")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN')")
    @PostMapping("/{clubId}/member/{memberId}/kick")
    public Result<Void> kickMember(@PathVariable Long clubId, @PathVariable Long memberId) {
        Long operatorId = SecurityUtils.getCurrentUserId();
        clubMemberService.removeMember(memberId, clubId, operatorId);
        return Result.success("已踢出成员", null);
    }

    @Operation(summary = "设置成员角色")
    @PreAuthorize("hasAnyRole('ADMIN', 'CLUB_ADMIN')")
    @PostMapping("/member/{memberId}/role")
    public Result<Void> setMemberRole(
            @PathVariable Long memberId,
            @RequestParam String role) {
        Long operatorId = SecurityUtils.getCurrentUserId();
        clubMemberService.setMemberRole(memberId, role, operatorId);
        return Result.success("已更新成员角色", null);
    }
}
